package com.hw.controller;

import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.hw.utils.SmsSendUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.aliyun.tea.*;

import javax.annotation.Resource;

/**
 * @program: springboot-alibaba-sms
 * @description: 发送短信验证码的测试控制器
 * @author: Henry.zhang
 * @create: 2022-09-06 11:16
 */
@RestController
@RequestMapping("sms")
public class SmsDemoController {
    /*
    属性列表
    */
    @Resource
    private SmsSendUtil smsSendUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @RequestMapping("send")
    public String demo(@RequestParam("phone") String phone){
        //给传入的手机号发送验证码
        //1.生成验证码
        Random random = new Random();
        int code = random.nextInt(9999);

        //2.调用api发送验证码
        smsSendUtil.send(phone,code);

        //3.把验证码保存至 redis 并给其 5分钟的过期时间
        stringRedisTemplate.opsForValue().set("user:login:"+phone,String.valueOf(code),5, TimeUnit.MINUTES);

        return "ok";

    }


    @RequestMapping("check")
    public String check(@RequestParam("phone") String phone,
                        @RequestParam("code") String code){
        //验证用户输入的验证码
        String codeStr = stringRedisTemplate.opsForValue().get("user:login:" + phone);

        if(codeStr == null){
            return "验证码失效";
        }

        if(!codeStr.equals(code)){
            return "验证码输入错误";
        }


        return "check ok";

    }





}
